// 系统前置接口，无需用户token认证
import axios from 'axios';
import { get, post, getNormal, postNormal } from '@common/ajax';
import { setInfo, getInfo } from '@common/storage';
import { envTarget, platformTruth } from '@common/environment';
import logger from '@common/logger';

import { setUserTokenCookie, setUserMemberIdCookie, getBrandIdCookie, getAppIdCookie, getUserOpenIdCookie, getUserInfoCookie, getComponentAppId, getAuthAppIdCookie } from '@biztools/info';

import urls from '@common/url';
import MD5 from '@common/md5';

/**
 * 获取 app 需要的信息，appid & comId
 * @param {String | Number} storeId 门店 id
 */
export const getAppInfo = async (storeId) => {
    const scene = envTarget();
    const res = await getNormal(urls.appInfo, {
        store_id: storeId,
        scene,
    });
    return res;
};

/**
 * 通过公众号appid获取，component_app_id
 * @param {String} appId 公众号appid
 */
export const getPublicInfo = async (appId) => {
    const scene = envTarget();
    const res = await getNormal(urls.appComponentInfo, {
        app_id: appId,
        scene,
    });
    return res;
};

/**
 * 通过授权组id获取授权相关的信息
 * @param {String | Number} authId 授权组id
 */
export const getAuthGroupInfo = async (authId, alipayAuthId) => {
    const scene = envTarget();
    const res = await getNormal(urls.authInfo, {
        auth_group_id: authId,
        alipay_auth_id: alipayAuthId,
        scene,
    });
    return res;
};

export const getWechatMiniAuthParam = async (appid, sgId) => {
    const scene = envTarget();
    const param = {
        scene,
        appid,
        sg_id: sgId,
    };
    const res = await postNormal(urls.wechatMiniAuthParam, param);
    return res;
};

/**
 *
 * @param {String} appId appid
 * @param {*} code
 * @param {*} sgId
 */
export const getMemberIdV2 = async (code) => {
    if (!code) {
        return null;
    }
    // 渠道值
    const scene = envTarget();
    let param = {
        code,
        scene,
        openid: getUserOpenIdCookie(),
        auth_appid: getAuthAppIdCookie(),
        appid: getAppIdCookie(),
        sg_id: getBrandIdCookie(),
        component_appid: getComponentAppId(),
    };
    const { member_id, user_key, token, reg_required } = await postNormal(urls.checkMemberV2, param);
    if (reg_required) {
        // 需要重新调用注册，更新用户信息
        setInfo('userKey', user_key);
        return false;
    } else {
        // 设置用户token
        setUserTokenCookie(token);
        setUserMemberIdCookie(member_id);
        return member_id;
    }
};

/**
 * 获取会员 memberid
 * @param {String} appId 从后台接口获取到的当前的门店所用的 appid
 * @param {String} code 微信认证后返回的 code 或者从支付宝返回的 auth_code
 */
export const getMemberId = async (appId, code, sgId) => {
    if (!code) {
        return null;
    }
    // 渠道值
    const scene = envTarget();
    const { isAlipay } = platformTruth();
    let param = {
        app_id: appId,
        code,
        sg_id: sgId,
        scene,
    };
    if (isAlipay) {
        param = {
            ...param,
            code_type: 'isv',
            component_app_id: getComponentAppId(),
        };
    }
    logger.info('调用的参数为：', param);
    const { member_id, user_key, token } = await postNormal(urls.checkMember, param);
    logger.info('返回参数：', member_id, user_key, token);
    if (member_id) {
        // 设置用户token
        setUserTokenCookie(token);
        setUserMemberIdCookie(member_id);
        return member_id;
    } else {
        setInfo('userKey', user_key);
        return null;
    }
};

/**
 * 小程序获取用户memberid
 */
export const getMemberIdMini = async () => {
    // 渠道值
    const scene = envTarget();
    const appId = getAppIdCookie();
    const openId = getUserOpenIdCookie();
    const userInfo = getUserInfoCookie();
    let param = {
        app_id: appId,
        sg_id: getBrandIdCookie(),
        scene,
        open_id: openId,
    };
    if (userInfo && userInfo !== '') {
        param = {
            ...param,
            user_info: userInfo,
        };
    }
    const { member_id, user_key, token } = await postNormal(urls.checkMember, param);
    if (member_id) {
        // 设置用户token
        setUserTokenCookie(token);
        setUserMemberIdCookie(member_id);
        return member_id;
    } else {
        setInfo('userKey', user_key);
        return null;
    }
};

/**
 * 注册用户，返回 memberid
 * @param {String} token 当堂返回的用于生成 gopenid 的 token
 */
export const registerMember = async (token) => {
    const key = getInfo('userKey');
    const scene = envTarget();
    const param = {
        scene,
        app_id: getAppIdCookie(),
        user_key: key,
        sg_id: getBrandIdCookie(),
    };
    if (scene !== 'alipay') {
        param['g_token'] = token;
    }
    // 获取用户信息
    const res = await postNormal(urls.registerMember, param);
    if (res) {
        setUserTokenCookie(res.token);
        setUserMemberIdCookie(res.member_id);
        return res.member_id;
    } else {
        return null;
    }
};

export const miniRegisterMember = async () => {
    const scene = envTarget();
    const key = getInfo('userKey');
    const param = {
        g_appid: '',
        g_openid: '',
        scene,
        app_id: getAppIdCookie(),
        user_key: key,
        sg_id: getBrandIdCookie(),
    };
    // 生成签名
    const sign = createSign(param);
};
const createSign = (param) => {
    const keys = Object.keys(param).sort();
    let str = 'sign_str=*#@!20[20]%$';
    for (let i = 0; i < keys.length; i++) {
        const item = keys[i];
        str += `&${item}=${param[item]}`;
    }
    return MD5(str);
};

export const registerMemberOrUpdate = async (token) => {
    const key = getInfo('userKey');
    const scene = envTarget();
    const param = {
        scene,
        appid: getAppIdCookie(),
        user_key: key,
        sg_id: getBrandIdCookie(),
    };
    if (scene !== 'alipay') {
        param['g_token'] = token;
    }
    // 获取用户信息
    const res = await postNormal(urls.registerMemberV2, param);
    if (res) {
        setUserTokenCookie(res.token);
        setUserMemberIdCookie(res.member_id);
        return res.member_id;
    } else {
        return null;
    }
};

/**
 * 获取品牌列表
 * @param {String} appId 小程序id
 */
export const getBrandList = async (appId) => {
    const res = await axios.get(`${urls.brandList}?app_id=${appId}`);
    return res.data.data;
};

/**
 * 获取微信的配置信息
 */
export const getWXConfig = async () => {
    const res = await get(urls.wechatConfig, {
        url: window.location.href,
    });
    return res.params;
};

/**
 * 获取会员码
 * @param {String} token memberInfo 的 token
 */
export const getMemberQRCode = async (token) => {
    const res = await post(urls.memberQrcode, {
        token,
    });
    return res.hash;
};
